package czh.cocoa.ui;

import czh.cocoa.foundation.NSMutableArray;
import czh.cocoa.foundation.NSObject;
import czh.cocoa.foundation.NSSelector;
import czh.cocoa.foundation.NSSet;

public class UIGestureRecognizer extends NSObject {

	public final static int UIGestureRecognizerStatePossible = 0;
	public final static int UIGestureRecognizerStateBegan = 1;
	public final static int UIGestureRecognizerStateChanged = 2;
	public final static int UIGestureRecognizerStateEnded = 3;
	public final static int UIGestureRecognizerStateCancelled = 4;
	public final static int UIGestureRecognizerStateFailed = 5;
	
	private int mState;
	
	private UIView mView;
	
	private NSMutableArray mActions;
	
	private boolean mDelaysTouchesBegan;
	
	private boolean mDelaysTouchesEnded;
	
	public UIGestureRecognizer() {
		mState = UIGestureRecognizerStatePossible;
		mActions = new NSMutableArray();
		mDelaysTouchesEnded = true;
	}
	
	public UIGestureRecognizer(NSObject target, NSSelector action) {
		this();
		addTargetAction(target, action);
	}
	
	public void addTargetAction(NSObject target, NSSelector action) {
		UITargetAction ta = new UITargetAction();
		ta.target = target;
		ta.action = action;
		mActions.addObject(ta);
	}
	
	public void removeTargetAction(NSObject target, NSSelector action) {
		for (NSObject o : mActions) {
			UITargetAction ta = (UITargetAction) o;
			if (ta.target == target && ta.action.isEqual(action)) {
				mActions.removeObject(ta);		
			}
		}
	}
	
	public void setState(int state) {
		if (mState != state || state == UIGestureRecognizerStateChanged) {
			mState = state;
			
			if(state == UIGestureRecognizerStateFailed) {
				CocoaView root = (CocoaView) UIApplication.sharedApplication().getRootView();
				root.removeGestureRecognizer(this); 
			} else if(state != UIGestureRecognizerStatePossible) {
				for (NSObject o : mActions) {
					UITargetAction ta = (UITargetAction) o;
					ta.action.perform(ta.target, this);
				}
			}
		}
	}
	
	public int state() {
		return mState;
	}
	
	public UIView view() {
		return mView;
	}
	
	void setView(UIView view) {
		mView = view;
	}
	
	public void touchesBeganWithEvent(NSSet touches, UIEvent event) {
		
	}
	
	public void touchesMovedWithEvent(NSSet touches, UIEvent event) {
		
	}
	
	public void touchesEndedWithEvent(NSSet touches, UIEvent event) {
		
	}
	
	public void touchesCancelledWithEvent(NSSet touches, UIEvent event) {
		
	}
	
	public void setDelaysTouchesBegan(boolean delayed) {
		mDelaysTouchesBegan = delayed;
	}
	
	public boolean delaysTouchesBegan() {
		return mDelaysTouchesBegan;
	}
	
	public void setDelaysTouchesEnded(boolean delayed) {
		mDelaysTouchesEnded = delayed;
	}
	
	public boolean delaysTouchesEnded() {
		return mDelaysTouchesEnded;
	}
	
	private class UITargetAction extends NSObject {
		
		public NSObject target;
		
		public NSSelector action;
	}
	
}
